﻿namespace JxcLite.Services;

/// <summary>
/// 系统基础数据服务接口。
/// </summary>
public interface IBaseDataService : IService
{
    /// <summary>
    /// 分页查询商品信息。
    /// </summary>
    /// <param name="criteria"></param>
    /// <returns></returns>
    Task<PagingResult<JxGoods>> QueryGoodsesAsync(PagingCriteria criteria);

    /// <summary>
    /// 获取所有商品信息。
    /// </summary>
    /// <returns></returns>
    Task<List<JxGoods>> GetGoodsesAsync();

    /// <summary>
    /// 批量删除商品信息。
    /// </summary>
    /// <param name="models"></param>
    /// <returns></returns>
    Task<Result> DeleteGoodsesAsync(List<JxGoods> models);

    /// <summary>
    /// 保存商品信息。
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    Task<Result> SaveGoodsAsync(UploadInfo<JxGoods> info);

    /// <summary>
    /// 分页查询客户或供应商信息，查询条件添加Type字段筛选。
    /// </summary>
    /// <param name="criteria"></param>
    /// <returns></returns>
    Task<PagingResult<JxPartner>> QueryPartnersAsync(PagingCriteria criteria);

    /// <summary>
    /// 批量删除客户或供应商信息。
    /// </summary>
    /// <param name="models"></param>
    /// <returns></returns>
    Task<Result> DeletePartnersAsync(List<JxPartner> models);

    /// <summary>
    /// 保存客户或供应商信息。
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    Task<Result> SavePartnerAsync(UploadInfo<JxPartner> info);
}

class BaseDataService(Context context) : ServiceBase(context), IBaseDataService
{
    #region JxGoods
    public Task<PagingResult<JxGoods>> QueryGoodsesAsync(PagingCriteria criteria)
    {
        return Database.QueryPageAsync<JxGoods>(criteria);
    }

    public Task<List<JxGoods>> GetGoodsesAsync()
    {
        return Database.QueryListAsync<JxGoods>(d => d.CompNo == CurrentUser.CompNo);
    }

    public async Task<Result> DeleteGoodsesAsync(List<JxGoods> models)
    {
        if (models == null || models.Count == 0)
            return Result.Error(Language.SelectOneAtLeast);

        var oldFiles = new List<string>();
        var result = await Database.TransactionAsync(Language.Delete, async db =>
        {
            foreach (var item in models)
            {
                await db.DeleteFilesAsync(item.Id, oldFiles);
                await db.DeleteAsync(item);
            }
        });
        if (result.IsValid)
            AttachFile.DeleteFiles(oldFiles);
        return result;
    }

    public async Task<Result> SaveGoodsAsync(UploadInfo<JxGoods> info)
    {
        var model = info.Model;
        var vr = model.Validate(Context);
        if (vr.IsValid)
        {
            if (await BaseDataRepository.ExistsGoodsCodeAsync(Database, model))
                vr.AddError("商品编码已存在！");
        }
        if (!vr.IsValid)
            return vr;

        var user = CurrentUser;
        var bizType = "GoodsFiles";
        var bizFiles = info.Files.GetAttachFiles(user, nameof(JxGoods.Files), bizType);
        return await Database.TransactionAsync(Language.Save, async db =>
        {
            await db.AddFilesAsync(bizFiles, model.Id, bizType);
            model.Files = $"{model.Id}_{bizType}";
            await db.SaveAsync(model);
        }, model);
    }
    #endregion

    #region JxPartner
    public Task<PagingResult<JxPartner>> QueryPartnersAsync(PagingCriteria criteria)
    {
        return Database.QueryPageAsync<JxPartner>(criteria);
    }

    public async Task<Result> DeletePartnersAsync(List<JxPartner> models)
    {
        if (models == null || models.Count == 0)
            return Result.Error(Language.SelectOneAtLeast);

        var oldFiles = new List<string>();
        var result = await Database.TransactionAsync(Language.Delete, async db =>
        {
            foreach (var item in models)
            {
                await db.DeleteFilesAsync(item.Id, oldFiles);
                await db.DeleteAsync(item);
            }
        });
        if (result.IsValid)
            AttachFile.DeleteFiles(oldFiles);
        return result;
    }

    public async Task<Result> SavePartnerAsync(UploadInfo<JxPartner> info)
    {
        var model = info.Model;
        var vr = model.Validate(Context);
        if (vr.IsValid)
        {
            if (await BaseDataRepository.ExistsPartnerNameAsync(Database, model))
                vr.AddError($"{model.Type}名称已存在！");
        }
        if (!vr.IsValid)
            return vr;

        var user = CurrentUser;
        var bizType = "PartnerFiles";
        var bizFiles = info.Files.GetAttachFiles(user, nameof(JxPartner.Files), bizType);
        return await Database.TransactionAsync(Language.Save, async db =>
        {
            await db.AddFilesAsync(bizFiles, model.Id, bizType);
            model.Files = $"{model.Id}_{bizType}";
            await db.SaveAsync(model);
        }, model);
    }
    #endregion
}